//
//  YCVCsDismissTransition.m
//  DemoTransition
//
//  Created by yunsheng on 15/7/23.
//  Copyright (c) 2015年 yunsheng. All rights reserved.
//

#import "YCVCsDismissTransition.h"

#import "YCModalViewController.h"
#import "YCModalDetailViewController.h"

@implementation YCVCsDismissTransition

-(NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.5;
}

-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    YCModalDetailViewController *fromVC = (YCModalDetailViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    YCModalViewController *toVC = (YCModalViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    [containerView addSubview:toVC.view];
    // chanage m34
    CATransform3D transform = CATransform3DIdentity;
    transform.m34 = -0.002;// 透视效果，要操作的这个对象要有旋转的角度，否则没有效果。当然,z方向上得有变化才会有透视效果
    containerView.layer.sublayerTransform = transform;
    // set anrchPoint and position
    CGRect initalFrame = [transitionContext initialFrameForViewController:fromVC];
    toVC.view.frame = initalFrame;
    toVC.view.layer.anchorPoint = CGPointMake(0, 0.5);
    toVC.view.layer.position = CGPointMake(0, initalFrame.size.height / 2.0);
    toVC.view.layer.transform = CATransform3DMakeRotation(-M_PI_2, 0, 1, 0);
    // add the effect of shadow
    CAGradientLayer *shadowLayer = [[CAGradientLayer alloc] init];
    shadowLayer.colors = @[(id)[UIColor colorWithWhite:0 alpha:1].CGColor, (id)[UIColor colorWithWhite:0 alpha:0.5].CGColor, (id)[UIColor colorWithWhite:1 alpha:0.5].CGColor];
    shadowLayer.startPoint = CGPointMake(0, 0.5);
    shadowLayer.endPoint = CGPointMake(1, 0.5);
    shadowLayer.frame = initalFrame;
    UIView *shadowView = [[UIView alloc] initWithFrame:initalFrame];
    shadowView.backgroundColor = [UIColor clearColor];
    [shadowView.layer addSublayer:shadowLayer];
    [fromVC.view addSubview:shadowView];
    shadowView.alpha = 1;
    // animation
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        toVC.view.layer.transform = CATransform3DIdentity;
        shadowView.alpha = 0;
    } completion:^(BOOL finished) {
        toVC.view.layer.anchorPoint = CGPointMake(0.5, 0.5);
        toVC.view.layer.position = CGPointMake(CGRectGetMidX(initalFrame), CGRectGetMidY(initalFrame));
        [shadowView removeFromSuperview];
        
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

@end
